package com.haven123.cloudapp.rabbitmq.listener;

import com.haven123.cloudapp.rabbitmq.Config.QueueConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author haven
 */
@Slf4j
@Component
public class QueueListener {

    @RabbitListener(queues = QueueConfig.queue_n1)
    public void listener1(String mail, Message message, Channel channel){
        log.info("listen1 i 我监听的是队列一");
        log.info(mail.toString());

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("ex",e);
        }
    }
    @RabbitListener(queues = QueueConfig.queue_n2)
    public void listener2(String mail, Message message, Channel channel){
        log.info("listen2");
        log.info(mail.toString());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("ex",e);
        }
    }
    @RabbitListener(queues = QueueConfig.queue_n3)
    public void listener3(String mail, Message message, Channel channel){
        log.info("listen3");
        log.info(mail.toString());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("ex",e);
        }
    }
    //由下面测试可以知道，不同的消费者同时监听同一个队列，还是会按照顺序进行消费，会相互阻塞，
    @RabbitListener(queues = QueueConfig.queue_n4)
    public void listener4(String mail, Message message, Channel channel){
        log.info("listen4");
        log.info("监听器1收到的i:"+mail.toString());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("ex",e);
        }
    }
    @RabbitListener(queues = QueueConfig.queue_n4)
    public void listener41(String mail, Message message, Channel channel){
        log.info("listen41");
        log.info("监听器2收到的i:"+mail.toString());
        try {
            //这里拒绝接受将把消息放入这个队列设置死信队列里面
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("ex",e);
        }
    }
}
